<?php

namespace PHPSpring\Annotation\Impl;

use PHPSpring\Core\RuntimeAnnotation;
use PHPSpring\Utils\Utils;

class Dao {

  public static function postInit($target, $entityClass=null) {
    if (empty($entityClass)) {
      return null;
    }
    $re = new \ReflectionClass($target);
    $property = $re->getProperty('entityClass');
    $property->setAccessible(true);
    $property->setValue($target, $entityClass);

    $annos = RuntimeAnnotation::getAnnotations($entityClass);
    $table = Utils::varToField($annos['class']['name']);
    if (isset($annos['class']['annos'])) {
      foreach ($annos['class']['annos'] as $annoName => $args) {
        $args = $args[1];
        if ($annoName == 'Entity' && count($args) > 0) {
          $table = $args[0];
        }
      }
    }
    $pk = '';
    $idType = \PHPSpring\Type\IDType::NONE;
    $properties = $annos['properties'];
    foreach ($annos['properties'] as $property => $anno) {
      if (isset($anno['annos']) && isset($anno['annos']['ID'])) {
        $args = $anno['annos']['ID'][1];
        if (empty($args)) {
          $idType = \PHPSpring\Type\IDType::AUTO;
        } else {
          $idTypeInfo = explode('::', $args[0]);
          $idTypeRe = new \ReflectionClass($idTypeInfo[0]);
          $idType = $idTypeRe->getConstant($idTypeInfo[1]);
        }
        $pk = $property;
        break;
      }
    }

    $pre = new \ReflectionClass($entityClass);
    $properties = $pre->getProperties();
    $fields = array();
    foreach ($properties as $property) {
      $type = Utils::typeToString($property->getType());
      $fields[$property->name] = array($type, $property->isPublic());
    }

    self::initProperties($target, $re, array(
      'entityClass' => $entityClass,
      'table' => $table,
      'pk'    => $pk,
      'idType' => $idType,
      'fields' => $fields
    ));
  }

  private static function initProperties($target, $targetRe, $kv) {
    foreach ($kv as $k => $v) {
      $property = $targetRe->getProperty($k);
      $property->setAccessible(true);
      $property->setValue($target, $v);
    }
  }
}
